﻿//Testing Purpose /Done in Welcome Screen

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using System.Xml.Linq;
using System.Data;
using System.Windows.Media.Imaging;
using System.IO;
using VAdvantage.Utility;
using VAdvantage.Model;
using System.Runtime.InteropServices.Automation;

namespace VAdvantage.KnowledgeBase
{
    public partial class Topic : SilverlightDesktop.Controls.Form
    {

        #region Decaration
        private bool isSingle = true;
        private SilverlightDesktop.Common.DoubleClickHelper helper;
        private List<KeyNamePair> lstSearch = null;

        #endregion

        public Topic()
        {
            InitializeComponent();
            Init();
        }

        // Executes when the user navigates to this page.
        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{
        //}

        #region Function

        private void Init()
        {
            GetData("Select * from K_TopicInfo");

            Ctx _ctx = Envs.GetCtx();
            chkWelcome.Content = Msg.GetMsg("WelcomeMessage");
            btnBack2.Text = Msg.GetMsg("Back");
            btnClose.Text = Msg.GetMsg("Close");
            btnClose2.Text = Msg.GetMsg("Close");
            txtGoto.Tag = Msg.GetMsg("Goto");

            btnClose.Icon = Envs.LoadImageSource("cancel.png");
            btnClose2.Icon = Envs.LoadImageSource("cancel.png");
            btnBack2.Icon = Envs.LoadImageSource("arrow-close.png");
        }

        private void GetData(string sql)
        {
            SetBusy(true);
            stTabular.Children.Clear();
            var clientTopic = Utility.AEnv.GetDataServiceDBClient();
            clientTopic.GetDataXMLCompleted += new EventHandler<System.Data.SqlClient.GetDataXMLCompletedEventArgs>(clientTopic_GetDataXMLCompleted);
            clientTopic.GetDataXMLAsync(sql, null, null);
            clientTopic.CloseAsync();
        }

        void clientTopic_GetDataXMLCompleted(object sender, System.Data.SqlClient.GetDataXMLCompletedEventArgs e)
        {
            SetBusy(false);
            if (e.Error != null || e.ServiceError != null)
            {
                return;
            }

           //InitilizeList
            if (lstSearch == null)
            {
                lstSearch = new List<KeyNamePair>();
                lstSearch.Add( new KeyNamePair(-1," "));
            }

            IDataReader dr = new DataReader();
            dr.SetData(e.Result);

            String name = "", desc = "", help = "";
            int id = 0, fkId = 0;

            BitmapSource img = null;
            Byte[] bArr = null;
            Object array = "";
            ObservableCollection<TopicInfo> list = new ObservableCollection<TopicInfo>();
            ImageTextControl ctrl = null;
            
            while (dr.Read())
            {
                name = dr["Name"].ToString();
                desc = dr["Description"].ToString();
                help = dr["Help"].ToString();
                array = dr["BinaryData"];
                if (array != null && array is byte[])
                {
                    MemoryStream ms = new MemoryStream((byte[])array);
                    img = new BitmapImage();
                    img.SetSource(ms);
                }

                id = Utility.Util.GetValueOfInt(dr["K_TopicInfo_ID"]);

                list.Add(new TopicInfo(id, name, desc, help, array));
                ctrl = new ImageTextControl(img, name, id);
                ctrl.Width = 150;
                ctrl.Height = 125;
                //ctrl.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                ctrl.Margin = new Thickness(1, 1, 10, 10);
                ctrl.Click += new EventHandler<MouseButtonEventArgs>(ctrl_Click);
                //ctrl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                stTabular.Children.Add(ctrl);

                lstSearch.Add(new KeyNamePair(id,name));
            }

            lstGrid.ItemsSource = list;

            
           if(cmbSearch.ItemsSource == null)
           {
               cmbSearch.ItemsSource = lstSearch;
               cmbSearch.SelectionChanged -=new SelectionChangedEventHandler(cmbSearch_SelectionChanged);
               cmbSearch.SelectionChanged +=new SelectionChangedEventHandler(cmbSearch_SelectionChanged);
           }
            //byte[] a=null;

            //MemoryStream aa = new MemoryStream(a);
            //BitmapImage d = new BitmapImage();
            //d.SetSource(aa);
            //Image dd=new Image();
            //dd.Source = d;

        }

        void cmbSearch_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbSearch.SelectedIndex < 1 || cmbSearch.SelectedItem == null)
            {
                GetData("Select * from K_TopicInfo");
            }
            else
            {
                KeyNamePair kp = cmbSearch.SelectedItem as KeyNamePair;
                GetData("Select * From K_TopicInfo Where K_TopicInfo_ID = " + kp.GetKey());
            }
        }

        void ctrl_Click(object sender, MouseButtonEventArgs e)
        {
            int id = ((ImageTextControl)sender).ID;
            GetRecord2(id);
            ShowSecondTab(true);
        }

        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            SwitchLayout();
        }

        private void SwitchLayout()
        {
            isSingle = !isSingle;

            if (isSingle)
            {
                grdTabular.Visibility = System.Windows.Visibility.Collapsed;
                grdDetail.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                grdDetail.Visibility = System.Windows.Visibility.Collapsed;
                grdTabular.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void ShowSecondTab(bool visible)
        {
            grdStep.Visibility = visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            grdTopic.Visibility = visible ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
        }

        private void SetBusy(bool isBusy)
        {
            busyIndicator.IsBusy = isBusy;

        }

        #region Tab2 Function
        private void GetRecord2(int id)
        {
            stepDetail.Clear();
            SetBusy(true);
            lstStep.ItemsSource = null;
            if (id == 0)
                return;
            var clientStep = Utility.AEnv.GetDataServiceDBClient();
            clientStep.GetDataXMLCompleted += new EventHandler<System.Data.SqlClient.GetDataXMLCompletedEventArgs>(clientStep_GetDataXMLCompleted);
            clientStep.GetDataXMLAsync(@" SELECT Name,Action, Description,Help,IsActive,IsReadonly,K_TopicInfo_ID, K_Instruction_ID, BinaryData,
                                          Coalesce(AD_Window_ID,AD_Task_ID,AD_Form_ID,AD_Process_ID,AD_Workbench_ID,AD_Workflow_ID) AS FKID 
                                            FROM K_Instruction
                                            WHERE K_TopicInfo_ID="+id +" AND IsActive = 'Y' Order by Seqno", null, null);
            clientStep.CloseAsync();
        }

        void clientStep_GetDataXMLCompleted(object sender, System.Data.SqlClient.GetDataXMLCompletedEventArgs e)
        {
            SetBusy(false);
            if (e.Error != null || e.ServiceError != null)
            {
                return;
            }

            IDataReader dr = new DataReader();
            dr.SetData(e.Result);

            String name = "", desc = "", help = "";
            int id = 0, fkId = 0;

            BitmapSource img = null;
            Byte[] bArr = null;
            Object array = "";
            ObservableCollection<TopicInfo> list = new ObservableCollection<TopicInfo>();
            ImageTextControl ctrl = null;

            while (dr.Read())
            {
                name = dr["Name"].ToString();
                desc = dr["Description"].ToString();
                help = dr["Help"].ToString();
                array = dr["BinaryData"];
                if (array != null && array is byte[])
                {
                    MemoryStream ms = new MemoryStream((byte[])array);
                    img = new BitmapImage();
                    img.SetSource(ms);
                }

                id = Utility.Util.GetValueOfInt(dr["K_Instruction_ID"]);
                fkId = Utility.Util.GetValueOfInt(dr["FKID"]);
                string action = Utility.Util.GetValueOfString(dr["Action"]);

                list.Add(new TopicInfo(id, name, desc, help, array, action, fkId,"","",""));
                //ctrl = new ImageTextControl(img, name,desc, id,action,fkId);
                //ctrl.Width = 150;
                //ctrl.Height = 100;
                ////ctrl.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                //ctrl.Margin = new Thickness(1, 1, 10, 10);
                //ctrl.Click += new EventHandler<MouseButtonEventArgs>(ctrl_Click);
                ////ctrl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                //stTabular.Children.Add(ctrl);
            }

            lstStep.ItemsSource = list;
            if (list.Count > 0)
            {
                lstStep.SelectedIndex = 0;
            }
            //byte[] a=null;

            //MemoryStream aa = new MemoryStream(a);
            //BitmapImage d = new BitmapImage();
            //d.SetSource(aa);
            //Image dd=new Image();
            //dd.Source = d;

        }

        private void SetStepDetailControl(int index)
        {
            if (index < 0 || lstStep.SelectedItem == null)
                return;

            TopicInfo tInfo = lstStep.SelectedItem as TopicInfo;

            stepDetail.SetParameter(tInfo);
            txtStepHeader.Text = tInfo.Name;


        }

        private void NavigateStep(int index)
        {
            if (lstStep.Items.Count == 0)
            {
                return;
            }

            int newIndex = lstStep.SelectedIndex;

            newIndex += index;

            if (newIndex < 0)
            {
                newIndex = lstStep.Items.Count - 1;
            }
            if (newIndex > lstStep.Items.Count - 1)
            {
                newIndex = 0;
            }
            lstStep.SelectedIndex = newIndex;

        }

        #endregion


        #endregion

        #region events

        private void btnClose2_Click(object sender, RoutedEventArgs e)
        {
            //grdStep.Visibility = System.Windows.Visibility.Collapsed;
            ShowSecondTab(false);
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Grid_Loaded(object sender, RoutedEventArgs e)
        {

            helper = new SilverlightDesktop.Common.DoubleClickHelper((FrameworkElement)sender);
            helper.DoubleClick += new EventHandler<MouseButtonEventArgs>(helper_DoubleClick);
            // helper.Click += new EventHandler<MouseButtonEventArgs>(helper_Click);

        }

        void helper_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            int id = 0;
            if (lstGrid.SelectedItem != null)
            {
                id = ((TopicInfo)lstGrid.SelectedItem).ID;
            }
            GetRecord2(id);
            ShowSecondTab(true);
        }

        private void lstStep_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SetStepDetailControl(lstStep.SelectedIndex);
        }

        private void btnLeftArrow_Click(object sender, RoutedEventArgs e)
        {
            //int index = lstStep.SelectedIndex;
            NavigateStep(-1);
        }

        private void btnBack2_Click(object sender, RoutedEventArgs e)
        {
            NavigateStep(-1);
        }

        private void grdRightArrow_Click(object sender, RoutedEventArgs e)
        {
            NavigateStep(1);
        }

        private void stepDetail_Click(object sender, MouseButtonEventArgs e)
        {
            NavigateStep(1);
        }

        private void imgSound_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (lstStep.SelectedIndex < 0 || lstStep.SelectedItem == null)
            {
                return;
            }

            TopicInfo tInfo = lstStep.SelectedItem as TopicInfo;

            if (App.Current.IsRunningOutOfBrowser && App.Current.HasElevatedPermissions)
            {
                dynamic textToSpeech = AutomationFactory.CreateObject("Sapi.SpVoice");
                textToSpeech.Volume = 100;
                textToSpeech.Speak(tInfo.Help);
            }
            else
            {
                SetBusy(true);

                var client = new SpeechService.SpeechServiceClient();

                client.SpeakCompleted += (o, ea) =>
                {
                    SetBusy(false);
                    VAdvantage.WavDecoder.WavMediaStreamSource audioStream = new VAdvantage.WavDecoder.WavMediaStreamSource(new MemoryStream(ea.Result));

                    _audioPlayer.SetSource(audioStream);
                };
                client.SpeakAsync(tInfo.Help);
                client.CloseAsync();
            }
        }
        #endregion

       
    }

    //public class TopicInfo
    //{

    //    public String Name
    //    {
    //        get;
    //        set;
    //    }

    //    public String Desc
    //    {
    //        get;
    //        set;
    //    }

    //    public String Help
    //    {
    //        get;
    //        set;
    //    }

    //    public ImageSource Icon
    //    {
    //        get;
    //        set;
    //    }

    //    public int ID
    //    {
    //        get;
    //        set;
    //    }

    //    public String Action
    //    {
    //        get;
    //        set;
    //    }

    //    public int FKID
    //    {
    //        get;
    //        set;
    //    }

    //    private object array;

    //    public TopicInfo(int Id, string name, string desc, string help, object array)
    //    {
    //        // TODO: Complete member initialization
    //        this.Name = name;
    //        this.Desc = desc;
    //        this.Help = help;
    //        this.array = array;
    //        if (array != null && array is byte[])
    //        {
    //            MemoryStream ms = new MemoryStream((byte[])array);
    //            BitmapSource img = new BitmapImage();
    //            img.SetSource(ms);
    //            Icon = img;
    //        }
    //        this.ID = Id;

    //    }
    //    public TopicInfo(int Id, string name, string desc, string help, object array, string action, int fkID)
    //    {
    //        // TODO: Complete member initialization
    //        this.Name = name;
    //        this.Desc = desc;
    //        this.Help = help;
    //        this.array = array;
    //        if (array != null && array is byte[])
    //        {
    //            MemoryStream ms = new MemoryStream((byte[])array);
    //            BitmapSource img = new BitmapImage();
    //            img.SetSource(ms);
    //            Icon = img;
    //        }
    //        this.ID = Id;
    //        this.Action = action;
    //        this.FKID = fkID;
    //    }

    //    public override string ToString()
    //    {
    //        return this.Name;
    //    }
    //}
}
